<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Search, Edit, Delete, View, Plus, Minus, Setting, Refresh, Coin } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const isAdmin = authStore.isAdmin
const isPartner = authStore.isPartner

const searchQuery = ref('')
const loading = ref(false)
const members = ref<any[]>([])

// 筛选相关
const statusFilter = ref('')
const roleFilter = ref('')
const memberLevelFilter = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 会员等级列表
const memberLevels = ref<Array<{ value: string; name: string; weight: number }>>([])

// 推荐人筛选
const referrerId = computed(() => route.query.referrerId as string | undefined)
const referrerName = computed(() => route.query.referrerName as string | undefined)

// 获取会员列表
async function fetchMembers() {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value
    }
    if (searchQuery.value) params.search = searchQuery.value
    if (statusFilter.value) params.status = statusFilter.value
    if (roleFilter.value) params.role = roleFilter.value
    if (memberLevelFilter.value) params.memberLevel = memberLevelFilter.value
    if (referrerId.value) params.referrerId = referrerId.value

    const { data } = await request.get('/api/admin/users', { params })
    members.value = data.users
    total.value = data.total
  } catch (error) {
    ElMessage.error('회원 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 获取会员等级列表
async function fetchMemberLevels() {
  try {
    const { data } = await request.get('/api/admin/member-levels')
    memberLevels.value = data
  } catch (error) {
    ElMessage.error('회원 등급 목록 가져오기 실패')
  }
}

function handleSearch() {
  currentPage.value = 1
  fetchMembers()
}

// 筛选处理
function handleFilterChange() {
  currentPage.value = 1
  fetchMembers()
}

// 清除推荐人筛选
function clearReferrer() {
  router.replace({
    query: {
      ...route.query,
      referrerId: undefined,
      referrerName: undefined
    }
  })
}

// 删除会员
const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `"${user.loginId}" 사용자를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.`,
      '사용자 삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    const response = await request.delete(`/api/admin/users/${user.id}`)
    const result = response.data

    if (result.success) {
      ElMessage.success(result.message || '사용자가 삭제되었습니다')
      fetchMembers() // 목록 새로고침
    } else {
      ElMessage.error(result.error || '삭제 실패')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 중 오류가 발생했습니다')
    }
  }
}

// 分页处理
function handlePageChange(page: number) {
  currentPage.value = page
  fetchMembers()
}

// 格式化角色
function getRoleLabel(role: string) {
  switch (role) {
    case 'admin': return '관리자'
    case 'partner': return '파트너'
    case 'user': return '일반 사용자'
    default: return role
  }
}

// 格式化会员等级
function getMemberLevelLabel(level: string) {
  const levelMap: Record<string, string> = {
    regular: '일반회원',
    silver: '실버',
    gold: '골드',
    diamond: '다이아',
    vip: 'VIP'
  }
  return levelMap[level] || '일반회원'
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString('ko-KR')
}

// 格式化积分
function formatPoints(points?: string) {
  return points ? parseInt(points).toLocaleString() : '0'
}

// 获取会员等级类型
function getMemberLevelType(level: string) {
  const typeMap: Record<string, string> = {
    regular: 'info',
    silver: '',
    gold: 'warning',
    diamond: 'success',
    vip: 'danger'
  }
  return typeMap[level] || 'info'
}

// 格式化性别
function getGenderLabel(gender?: string) {
  if (!gender) return '-'
  const genderMap: Record<string, string> = {
    male: '남성',
    female: '여성',
    other: '기타'
  }
  return genderMap[gender] || gender
}

// 用户详情相关
const showDetailDialog = ref(false)
const selectedMember = ref<any>(null)

// 用户编辑相关
const showEditDialog = ref(false)
const editLoading = ref(false)
const editForm = ref<{
  id?: string
  name?: string
  nickname?: string
  phone?: string
  gender?: string | null
  birthdate?: string | null
}>({})

// 积分管理相关
const showAddPointsDialog = ref(false)
const showSubtractPointsDialog = ref(false)
const pointsLoading = ref(false)
const pointsForm = ref({
  points: null as number | null,
  note: ''
})

// 会员等级管理相关
const showMemberLevelDialog = ref(false)
const memberLevelLoading = ref(false)
const memberLevelForm = ref({
  memberLevel: ''
})

// 试用重置相关
const trialLoading = ref(false)

// 查看会员详情
function viewMember(member: any) {
  selectedMember.value = member
  showDetailDialog.value = true
}

// 编辑会员
function editMember(member: any) {
  selectedMember.value = member
  editForm.value = {
    id: String(member.id),
    name: member.name || '',
    nickname: member.nickname || '',
    phone: member.phone || '',
    gender: member.gender || '',
    birthdate: member.birthdate ? String(member.birthdate).slice(0, 10) : ''
  }
  showEditDialog.value = true
}

// 保存用户编辑
async function saveUserEdit() {
  if (!editForm.value.id) return

  editLoading.value = true
  try {
    const payload: any = {
      name: editForm.value.name || null,
      nickname: editForm.value.nickname || null,
      phone: editForm.value.phone || null,
      gender: editForm.value.gender || null,
      birthdate: editForm.value.birthdate || null,
    }

    await request.put(`/api/admin/users/${editForm.value.id}`, payload)
    ElMessage.success('저장 성공')
    showEditDialog.value = false
    fetchMembers() // 刷新列表
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '저장 실패')
  } finally {
    editLoading.value = false
  }
}

// 打开添加积分弹窗
function openAddPoints(member: any) {
  selectedMember.value = member
  pointsForm.value = { points: null, note: '' }
  showAddPointsDialog.value = true
}

// 打开减少积分弹窗
function openSubtractPoints(member: any) {
  const currentBalance = Number(member?.wallet?.pointsBalance || 0)
  if (currentBalance <= 0) {
    ElMessage.warning('사용자의 포인트 잔액이 0이므로 차감할 수 없습니다')
    return
  }
  selectedMember.value = member
  pointsForm.value = { points: null, note: '' }
  showSubtractPointsDialog.value = true
}

// 添加积分
async function addPoints() {
  if (!pointsForm.value.points || pointsForm.value.points <= 0) {
    ElMessage.warning('유효한 포인트 수량을 입력하세요')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedMember.value?.nickname || selectedMember.value?.name || selectedMember.value?.loginId}에게 ${formatPoints(String(pointsForm.value.points))} 포인트를 추가하시겠습니까?`,
      '포인트 추가 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  pointsLoading.value = true
  try {
    await request.post(`/api/admin/users/${selectedMember.value.id}/points/add`, {
      points: pointsForm.value.points,
      note: pointsForm.value.note || '관리자 수동 포인트 추가'
    })

    ElMessage.success('포인트 추가 성공')
    showAddPointsDialog.value = false
    await fetchMembers() // 刷新列表
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '포인트 추가 실패')
  } finally {
    pointsLoading.value = false
  }
}

// 减少积分
async function subtractPoints() {
  if (!pointsForm.value.points || pointsForm.value.points <= 0) {
    ElMessage.warning('유효한 포인트 수량을 입력하세요')
    return
  }

  const currentBalance = Number(selectedMember.value?.wallet?.pointsBalance || 0)
  if (pointsForm.value.points > currentBalance) {
    ElMessage.warning('차감할 포인트가 현재 잔액을 초과할 수 없습니다')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedMember.value?.nickname || selectedMember.value?.name || selectedMember.value?.loginId}에게서 ${formatPoints(String(pointsForm.value.points))} 포인트를 차감하시겠습니까?`,
      '포인트 차감 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  pointsLoading.value = true
  try {
    await request.post(`/api/admin/users/${selectedMember.value.id}/points/subtract`, {
      points: pointsForm.value.points,
      note: pointsForm.value.note || '관리자 수동 포인트 차감'
    })

    ElMessage.success('포인트 차감 성공')
    showSubtractPointsDialog.value = false
    await fetchMembers() // 刷新列表
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '포인트 차감 실패')
  } finally {
    pointsLoading.value = false
  }
}

// 打开等级修改弹窗
function openEditMemberLevel(member: any) {
  selectedMember.value = member
  memberLevelForm.value = { memberLevel: member.memberLevel || 'regular' }
  showMemberLevelDialog.value = true
}

// 更新会员等级
async function updateMemberLevel() {
  if (!memberLevelForm.value.memberLevel) {
    ElMessage.warning('등급을 선택하세요')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${selectedMember.value?.nickname || selectedMember.value?.name || selectedMember.value?.loginId}의 등급을 ${getMemberLevelLabel(memberLevelForm.value.memberLevel)}로 변경하시겠습니까?`,
      '등급 변경 확인',
      { type: 'warning' }
    )
  } catch {
    return
  }

  memberLevelLoading.value = true
  try {
    await request.put(`/api/admin/users/${selectedMember.value.id}/member-level`, {
      memberLevel: memberLevelForm.value.memberLevel
    })

    ElMessage.success('회원 등급이 성공적으로 변경되었습니다')
    showMemberLevelDialog.value = false
    await fetchMembers() // 刷新列表
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '등급 변경 실패')
  } finally {
    memberLevelLoading.value = false
  }
}

// 切换用户状态
async function toggleUserStatus(member: any) {
  const newStatus = member.status === 'active' ? 'banned' : 'active'
  const actionText = member.status === 'active' ? '비활성화' : '활성화'
  const resultText = member.status === 'active' ? '비활성화됨' : '활성화됨'

  try {
    await ElMessageBox.confirm(
      `${member.nickname || member.name || member.loginId}을(를) ${actionText}하시겠습니까?`,
      '상태 변경 확인',
      { type: 'warning' }
    )

    await request.put(`/api/admin/users/${member.id}/status`, {
      status: newStatus
    })

    ElMessage.success(resultText)
    await fetchMembers() // 刷新列表
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.error || '작업 실패')
    }
  }
}

// 重置试用状态
async function resetTrialForUser(member: any) {
  try {
    await ElMessageBox.confirm(
      `사용자 ${member.nickname || member.name || member.loginId}의 체험 상태를 재설정하시겠습니까?`,
      '재설정 확인',
      { type: 'warning' }
    )

    trialLoading.value = true
    await request.post(`/api/admin/users/${member.id}/reset-trial`)
    ElMessage.success('체험 상태가 재설정되었습니다')
    await fetchMembers() // 刷新列表
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.response?.data?.error || error?.message || '재설정 실패')
    }
  } finally {
    trialLoading.value = false
  }
}

onMounted(() => {
  fetchMembers()
  fetchMemberLevels()
})
</script>

<template>
  <div class="members-view">
    <div class="page-header">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <User />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">회원 관리</h1>
          <p class="page-subtitle">사용자 계정을 관리합니다</p>
        </div>
      </div>
    </div>

    <div class="page-content">
      <!-- 推荐人筛选提示 -->
      <el-alert
        v-if="referrerId"
        :title="`현재 필터: 파트너 ${referrerName || referrerId}`"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 12px"
      >
        <template #default>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>현재 필터: 파트너 {{ referrerName || referrerId }}</span>
            <el-button size="small" type="warning" plain @click="clearReferrer">필터 제거</el-button>
          </div>
        </template>
      </el-alert>

      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="로그인 ID, 이메일, 이름, 닉네임 또는 휴대폰 번호 검색"
          :prefix-icon="Search"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" :loading="loading" />
          </template>
        </el-input>
      </div>

      <!-- 筛选栏 -->
      <div class="filter-section">
        <div class="filter-row">
          <el-select
            v-model="statusFilter"
            placeholder="상태"
            clearable
            size="small"
            @change="handleFilterChange"
          >
            <el-option label="정상" value="active" />
            <el-option label="비활성화됨" value="banned" />
          </el-select>

          <el-select
            v-model="roleFilter"
            placeholder="역할"
            clearable
            size="small"
            @change="handleFilterChange"
          >
            <el-option label="일반 사용자" value="user" />
            <el-option label="파트너" value="partner" />
            <el-option label="관리자" value="admin" />
          </el-select>
        </div>

        <div class="filter-row">
          <el-select
            v-model="memberLevelFilter"
            placeholder="회원 등급"
            clearable
            size="small"
            @change="handleFilterChange"
          >
            <el-option
              v-for="level in memberLevels"
              :key="level.value"
              :label="level.name"
              :value="level.value"
            />
          </el-select>

          <div class="stats-info">
            <span class="total-count">총 {{ total }}명</span>
          </div>
        </div>
      </div>

      <!-- 会员列表 -->
      <div class="members-list" v-loading="loading">
        <div v-for="member in members" :key="member.id" class="member-card">
          <div class="member-info">
            <el-avatar :size="40" :icon="User" />
            <div class="member-details">
              <div class="member-name">
                <span>{{ member.name || member.loginId }}</span>
                <span v-if="member.nickname" class="nickname">({{ member.nickname }})</span>
              </div>
              <div class="member-email">{{ member.email }}</div>
              <div class="member-extra-info">
                <div v-if="member.referrer" class="referrer-info">
                  <span class="label">추천인:</span>
                  <span class="referrer">{{ member.referrer.loginId }}</span>
                  <el-tag v-if="member.referrer.partnerProfile?.referralCode" size="small" effect="plain">
                    {{ member.referrer.partnerProfile.referralCode }}
                  </el-tag>
                </div>
                <div class="points-info">
                  <span class="label">포인트:</span>
                  <span class="points">{{ formatPoints(member.wallet?.pointsBalance) }}</span>
                </div>
                <div v-if="member.trial" class="trial-info">
                  <span class="label">체험:</span>
                  <el-tag size="small" :type="member.trial.ended ? 'danger' : 'warning'">
                    {{ member.trial.ended ? '종료됨' : '진행 중' }}
                  </el-tag>
                </div>
              </div>
              <div class="member-meta">
                <el-tag size="small" :type="member.status === 'active' ? 'success' : 'info'">
                  {{ member.status === 'active' ? '정상' : '비활성화됨' }}
                </el-tag>
                <el-tag size="small" :type="member.role === 'admin' ? 'danger' : member.role === 'partner' ? 'warning' : 'info'">
                  {{ getRoleLabel(member.role) }}
                </el-tag>
                <el-tag size="small" :type="getMemberLevelType(member.memberLevel)">
                  {{ getMemberLevelLabel(member.memberLevel) }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="member-actions">
            <el-button size="small" :icon="View" circle @click="viewMember(member)" />
            <el-button v-if="isAdmin" size="small" :icon="Edit" circle @click="editMember(member)" />
            <el-dropdown v-if="isAdmin || isPartner" trigger="click" placement="bottom-end">
              <el-button size="small" :icon="Setting" circle />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openAddPoints(member)">
                    <el-icon><Plus /></el-icon>
                    포인트 추가
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="openSubtractPoints(member)"
                    :disabled="Number(member.wallet?.pointsBalance || 0) <= 0"
                  >
                    <el-icon><Minus /></el-icon>
                    포인트 차감
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="openEditMemberLevel(member)">
                    <el-icon><Setting /></el-icon>
                    등급 수정
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="toggleUserStatus(member)"
                    :class="member.status === 'active' ? 'danger-item' : 'success-item'"
                  >
                    <el-icon v-if="member.status === 'active'"><Minus /></el-icon>
                    <el-icon v-else><Plus /></el-icon>
                    {{ member.status === 'active' ? '비활성화' : '활성화' }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="resetTrialForUser(member)">
                    <el-icon><Refresh /></el-icon>
                    체험 재설정
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              v-if="isAdmin && member.role !== 'admin'"
              size="small"
              type="danger"
              :icon="Delete"
              circle
              @click="deleteUser(member)"
            />
          </div>
        </div>

        <div v-if="!loading && members.length === 0" class="empty-state">
          <el-icon size="48"><User /></el-icon>
          <p>등록된 회원이 없습니다</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="회원 상세 정보"
      width="90%"
      :show-close="true"
      :close-on-click-modal="true"
    >
      <div v-if="selectedMember" class="member-detail">
        <div class="detail-header">
          <el-avatar :size="60" :icon="User" />
          <div class="header-info">
            <h3>{{ selectedMember.name || selectedMember.loginId }}</h3>
            <p v-if="selectedMember.nickname" class="nickname-text">{{ selectedMember.nickname }}</p>
            <div class="status-tags">
              <el-tag :type="selectedMember.status === 'active' ? 'success' : 'info'">
                {{ selectedMember.status === 'active' ? '정상' : '비활성화됨' }}
              </el-tag>
              <el-tag :type="selectedMember.role === 'admin' ? 'danger' : selectedMember.role === 'partner' ? 'warning' : 'info'">
                {{ getRoleLabel(selectedMember.role) }}
              </el-tag>
              <el-tag :type="getMemberLevelType(selectedMember.memberLevel)">
                {{ getMemberLevelLabel(selectedMember.memberLevel) }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="detail-section">
            <h4>기본 정보</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">로그인 ID:</span>
                <span class="value">{{ selectedMember.loginId }}</span>
              </div>
              <div class="detail-item">
                <span class="label">이메일:</span>
                <span class="value">{{ selectedMember.email }}</span>
              </div>
              <div class="detail-item">
                <span class="label">성명:</span>
                <span class="value">{{ selectedMember.name || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">닉네임:</span>
                <span class="value">{{ selectedMember.nickname || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">휴대폰 번호:</span>
                <span class="value">{{ selectedMember.phone || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">성별:</span>
                <span class="value">{{ getGenderLabel(selectedMember.gender) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">생일:</span>
                <span class="value">{{ selectedMember.birthdate ? formatDate(selectedMember.birthdate) : '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">가입 시간:</span>
                <span class="value">{{ formatDate(selectedMember.createdAt) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section" v-if="selectedMember.referrer">
            <h4>추천인 정보</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">추천인:</span>
                <span class="value referrer-name">{{ selectedMember.referrer.loginId }}</span>
              </div>
              <div class="detail-item" v-if="selectedMember.referrer.partnerProfile?.referralCode">
                <span class="label">추천 코드:</span>
                <span class="value referral-code">{{ selectedMember.referrer.partnerProfile.referralCode }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>포인트 & 체험 정보</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">포인트 잔액:</span>
                <span class="value points-balance">{{ formatPoints(selectedMember.wallet?.pointsBalance) }}</span>
              </div>
              <div class="detail-item" v-if="selectedMember.trial">
                <span class="label">체험 상태:</span>
                <el-tag :type="selectedMember.trial.ended ? 'danger' : 'warning'">
                  {{ selectedMember.trial.ended ? '종료됨' : '진행 중' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="showDetailDialog = false">닫기</el-button>
      </template>
    </el-dialog>

    <!-- 用户编辑弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="회원 정보 편집"
      width="90%"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="selectedMember" class="edit-form-container">
        <div class="edit-header">
          <el-avatar :size="50" :icon="User" />
          <div class="edit-header-info">
            <h4>{{ selectedMember.loginId }}</h4>
            <p>{{ selectedMember.email }}</p>
          </div>
        </div>

        <el-form :model="editForm" label-position="top" class="edit-form">
          <el-form-item label="성명">
            <el-input
              v-model="editForm.name"
              placeholder="성명을 입력하세요"
              clearable
            />
          </el-form-item>

          <el-form-item label="닉네임">
            <el-input
              v-model="editForm.nickname"
              placeholder="닉네임을 입력하세요"
              clearable
            />
          </el-form-item>

          <el-form-item label="휴대폰 번호">
            <el-input
              v-model="editForm.phone"
              placeholder="휴대폰 번호를 입력하세요"
              clearable
            />
          </el-form-item>

          <el-form-item label="성별">
            <el-select
              v-model="editForm.gender"
              placeholder="성별을 선택하세요"
              clearable
              style="width: 100%"
            >
              <el-option label="남성" value="male" />
              <el-option label="여성" value="female" />
              <el-option label="기타" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="생일">
            <el-date-picker
              v-model="editForm.birthdate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="날짜를 선택하세요"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="edit-footer">
          <el-button @click="showEditDialog = false">취소</el-button>
          <el-button
            type="primary"
            :loading="editLoading"
            @click="saveUserEdit"
          >
            저장
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加积分弹窗 -->
    <el-dialog
      v-model="showAddPointsDialog"
      title="포인트 추가"
      width="90%"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="selectedMember" class="points-form-container">
        <div class="points-header">
          <el-avatar :size="50" :icon="User" />
          <div class="points-header-info">
            <h4>{{ selectedMember.nickname || selectedMember.name || selectedMember.loginId }}</h4>
            <p class="current-balance">현재 잔액: {{ formatPoints(selectedMember.wallet?.pointsBalance || '0') }}</p>
          </div>
        </div>

        <el-form :model="pointsForm" label-position="top" class="points-form">
          <el-form-item label="추가 포인트" required>
            <el-input-number
              v-model="pointsForm.points"
              :min="1"
              style="width: 100%"
              placeholder="추가할 포인트 수량을 입력하세요"
              @keyup.enter="addPoints"
            />
          </el-form-item>

          <el-form-item label="비고">
            <el-input
              v-model="pointsForm.note"
              type="textarea"
              :rows="3"
              placeholder="포인트 추가 사유 또는 비고 (선택사항)"
              maxlength="200"
              show-word-limit
              @keyup.enter="addPoints"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="points-footer">
          <el-button @click="showAddPointsDialog = false">취소</el-button>
          <el-button
            type="primary"
            :loading="pointsLoading"
            @click="addPoints"
          >
            추가 확인
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 减少积分弹窗 -->
    <el-dialog
      v-model="showSubtractPointsDialog"
      title="포인트 차감"
      width="90%"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="selectedMember" class="points-form-container">
        <div class="points-header">
          <el-avatar :size="50" :icon="User" />
          <div class="points-header-info">
            <h4>{{ selectedMember.nickname || selectedMember.name || selectedMember.loginId }}</h4>
            <p class="current-balance">현재 잔액: {{ formatPoints(selectedMember.wallet?.pointsBalance || '0') }}</p>
          </div>
        </div>

        <el-form :model="pointsForm" label-position="top" class="points-form">
          <el-form-item label="차감 포인트" required>
            <el-input-number
              v-model="pointsForm.points"
              :min="1"
              :max="Math.max(1, Number(selectedMember?.wallet?.pointsBalance || 0))"
              style="width: 100%"
              placeholder="차감할 포인트 수량을 입력하세요"
              @keyup.enter="subtractPoints"
            />
          </el-form-item>

          <el-form-item label="비고">
            <el-input
              v-model="pointsForm.note"
              type="textarea"
              :rows="3"
              placeholder="포인트 차감 사유 또는 비고 (선택사항)"
              maxlength="200"
              show-word-limit
              @keyup.enter="subtractPoints"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="points-footer">
          <el-button @click="showSubtractPointsDialog = false">취소</el-button>
          <el-button
            type="danger"
            :loading="pointsLoading"
            @click="subtractPoints"
          >
            차감 확인
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 회원 등급 수정 弹窗 -->
    <el-dialog
      v-model="showMemberLevelDialog"
      title="회원 등급 수정"
      width="90%"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="selectedMember" class="level-form-container">
        <div class="level-header">
          <el-avatar :size="50" :icon="User" />
          <div class="level-header-info">
            <h4>{{ selectedMember.nickname || selectedMember.name || selectedMember.loginId }}</h4>
            <p class="current-level">현재 등급: {{ getMemberLevelLabel(selectedMember.memberLevel || 'regular') }}</p>
          </div>
        </div>

        <el-form :model="memberLevelForm" label-position="top" class="level-form">
          <el-form-item label="새 등급" required>
            <el-select
              v-model="memberLevelForm.memberLevel"
              placeholder="등급을 선택하세요"
              style="width: 100%"
            >
              <el-option
                v-for="level in memberLevels"
                :key="level.value"
                :label="level.name"
                :value="level.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="level-footer">
          <el-button @click="showMemberLevelDialog = false">취소</el-button>
          <el-button
            type="primary"
            :loading="memberLevelLoading"
            @click="updateMemberLevel"
          >
            수정 확인
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.members-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

.page-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-section {
  width: 100%;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.filter-row .el-select {
  flex: 1;
  min-width: 0;
}

.stats-info {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.total-count {
  font-size: 12px;
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.members-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.member-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 4px;
}

.nickname {
  font-size: 12px;
  color: var(--el-text-color-regular);
  font-weight: normal;
}

.member-email {
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-bottom: 4px;
}

.member-extra-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 6px;
  font-size: 11px;
}

.member-extra-info .label {
  color: var(--el-text-color-secondary);
  margin-right: 4px;
}

.referrer-info, .points-info, .trial-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.referrer {
  color: var(--el-color-primary);
  font-weight: 500;
}

.points {
  color: var(--el-color-success);
  font-weight: 500;
  font-family: monospace;
}

.member-meta {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.member-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-shrink: 0;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    gap: 12px;
  }

  .filter-row .el-select {
    width: 100%;
  }

  .member-card {
    padding: 12px;
  }

  .member-info {
    gap: 10px;
  }

  .member-details {
    min-width: 0;
    flex: 1;
  }

  .member-name {
    font-size: 13px;
  }

  .member-email {
    font-size: 11px;
  }

  .member-extra-info {
    font-size: 10px;
  }

  .member-actions {
    gap: 6px;
  }

  .member-actions .el-button {
    padding: 6px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .page-content {
    gap: 12px;
  }

  .search-section .el-input {
    font-size: 14px;
  }

  .member-card {
    padding: 10px;
  }

  .member-info {
    gap: 8px;
  }

  .member-extra-info {
    display: none; /* 在超小屏幕上隐藏额外信息 */
  }

  .member-meta .el-tag {
    font-size: 10px;
    padding: 0 4px;
    height: 20px;
    line-height: 18px;
  }
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--el-text-color-secondary);
}

.empty-state p {
  margin: 8px 0 0 0;
  font-size: 14px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.placeholder-notice {
  margin-top: 20px;
}

/* 用户详情弹窗样式 */
.member-detail {
  padding: 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

.header-info {
  flex: 1;
}

.header-info h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.nickname-text {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.status-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  font-weight: 500;
  min-width: 80px;
}

.detail-item .value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  text-align: right;
  word-break: break-all;
}

.referrer-name {
  color: var(--el-color-primary) !important;
  font-weight: 500;
}

.referral-code {
  font-family: monospace;
  background: var(--el-fill-color-light);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.points-balance {
  color: var(--el-color-success) !important;
  font-weight: 600;
  font-family: monospace;
}

/* 暗黑模式适配 */
:root.dark .member-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .detail-header {
  border-bottom-color: var(--el-border-color);
}

:root.dark .detail-section h4 {
  border-bottom-color: var(--el-border-color);
}

:root.dark .detail-item {
  border-bottom-color: var(--el-border-color-extra-light);
}

/* 用户编辑弹窗样式 */
.edit-form-container {
  padding: 0;
}

.edit-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

.edit-header-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.edit-header-info p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.edit-form {
  margin: 0;
}

.edit-form .el-form-item {
  margin-bottom: 20px;
}

.edit-form .el-form-item__label {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.edit-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 暗黑模式适配 - 编辑弹窗 */
:root.dark .edit-header {
  border-bottom-color: var(--el-border-color);
}

/* 积分管理弹窗样式 */
.points-form-container {
  padding: 0;
}

.points-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

.points-header-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.current-balance {
  margin: 0;
  font-size: 14px;
  color: var(--el-color-success);
  font-weight: 500;
  font-family: monospace;
}

.points-form {
  margin: 0;
}

.points-form .el-form-item {
  margin-bottom: 20px;
}

.points-form .el-form-item__label {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.points-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 暗黑模式适配 - 积分弹窗 */
:root.dark .points-header {
  border-bottom-color: var(--el-border-color);
}

/* 등급 관리 弹窗样式 */
.level-form-container {
  padding: 0;
}

.level-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

.level-header-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.current-level {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.level-form {
  margin: 0;
}

.level-form .el-form-item {
  margin-bottom: 20px;
}

.level-form .el-form-item__label {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.level-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 暗黑模式适配 - 등급 弹窗 */
:root.dark .level-header {
  border-bottom-color: var(--el-border-color);
}

/* 下拉菜单项样式 */
.danger-item {
  color: var(--el-color-danger) !important;
}

.success-item {
  color: var(--el-color-success) !important;
}

/* 触摸友好优化 */
.member-card {
  transition: all 0.2s ease;
  cursor: pointer;
}

.member-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.member-card:active {
  transform: translateY(0);
}

/* 按钮触摸优化 */
.member-actions .el-button {
  min-width: 36px;
  min-height: 36px;
  transition: all 0.2s ease;
}

.member-actions .el-button:active {
  transform: scale(0.95);
}

/* 下拉菜单触摸优化 */
.el-dropdown-menu .el-dropdown-menu__item {
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.4;
}

/* 弹窗触摸优化 */
.el-dialog {
  margin: 5vh auto;
}

@media (max-width: 768px) {
  .el-dialog {
    margin: 2vh auto;
    max-height: 96vh;
  }

  .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }
}

/* 表单输入优化 */
.el-input__inner,
.el-textarea__inner,
.el-select .el-input__inner {
  font-size: 16px; /* 防止iOS缩放 */
}

@media (max-width: 768px) {
  .el-input__inner,
  .el-textarea__inner,
  .el-select .el-input__inner {
    padding: 12px 15px;
    height: 44px;
    line-height: 20px;
  }

  .el-textarea__inner {
    height: auto;
    min-height: 44px;
  }
}
</style>
